import storage from '@/utils/storage'

function onColorChange(colors) {
  // document.documentElement 是全局变量时
  const el = document.documentElement
  // const el = document.getElementById('xxx')

  // 获取 css 变量
  getComputedStyle(el).getPropertyValue(`--el-color-primary`)

  // 设置 css 变量
  el.style.setProperty('--el-color-primary', colors['500'])
  el.style.setProperty('--el-color-primary-light-3', colors['400'])
  el.style.setProperty('--el-color-primary-light-5', colors['300'])
  el.style.setProperty('--el-color-primary-light-7', colors['200'])
  el.style.setProperty('--el-color-primary-light-8', colors['100'])
  el.style.setProperty('--el-color-primary-light-9', colors['50'])
}

const state = () => ({
  dark: false,
  size: 'default',
  color: {
    name: 'default',
    colors: {
      50: '#ecf5ff',
      100: '#d9ecff',
      200: '#c6e2ff',
      300: '#a0cfff',
      400: '#79bbff',
      500: '#409EFF',
    },
  },
  menuBgTransparent: false,
  collapse: 0,
  keepAlive: true,
})

const mutations = {
  SET_DARK(state, dark) {
    state.dark = dark
    storage.set('theme.dark', dark)

    const classList = document.getElementsByTagName('html')[0].classList
    if (dark) {
      classList.add('dark')
    } else {
      classList.remove('dark')
    }
  },
  SET_SIZE(state, size) {
    state.size = size
    storage.set('theme.size', size)
  },
  SET_COLOR(state, color) {
    state.color = color
    storage.set('theme.color', color)

    onColorChange(color.colors)
  },
  SET_MENU_BG_TRANSPARENT(state, value) {
    state.menuBgTransparent = value
    storage.set('theme.menuBgTransparent', value)
  },
  SET_COLLASPE(state, value) {
    state.collapse = value
  },
  SET_KEEP_ALIVE(state, value) {
    state.keepAlive = value
    storage.set('theme.keepAlive', value)
  },
}

const actions = {
  initTheme({ commit }) {
    const dark = storage.get('theme.dark')
    if (dark != null) {
      commit('SET_DARK', dark)
    }

    const size = storage.get('theme.size')
    if (size != null) {
      commit('SET_SIZE', size)
    }

    const color = storage.get('theme.color')
    if (color != null) {
      commit('SET_COLOR', color)
    }

    const menuBgTransparent = storage.get('theme.menuBgTransparent')
    if (menuBgTransparent != null) {
      commit('SET_MENU_BG_TRANSPARENT', menuBgTransparent)
    }

    const keepAlive = storage.get('theme.keepAlive')
    if (keepAlive != null) {
      commit('SET_KEEP_ALIVE', keepAlive)
    }
  },
}

export default {
  namespaced: true,
  state: state,
  actions: actions,
  mutations: mutations,
}
